package org.budo.oceanengine.api.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.budo.oceanengine.api.entity.BaseRequest;
import org.budo.oceanengine.api.entity.BaseResponse;
import org.budo.support.http.client.Request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

@Slf4j
public class RequestHandler {

    public static BaseResponse doGet(BaseRequest request) {
        return sendRequest(request, Request.GET);
    }

    public static BaseResponse doPost(BaseRequest request) {
        return sendRequest(request, Request.POST);
    }

    private static BaseResponse sendRequest(BaseRequest request, String method) {

        // 构造请求
        HttpEntityEnclosingRequestBase httpEntity = new HttpEntityEnclosingRequestBase() {
            @Override
            public String getMethod() {
                return method;
            }
        };

        httpEntity.setHeader("Access-Token", request.getAccessToken());

        if(request.getXDebugMode() != null){
            httpEntity.setHeader("X-Debug-Mode", request.getXDebugMode().toString());
        }

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;

        try {
            client = HttpClientBuilder.create().build();
            httpEntity.setURI(URI.create(request.getBaseUrl() + request.getApiUri()));
            httpEntity.setEntity(new StringEntity(JSONObject.toJSONString(request.getParamMap()), ContentType.APPLICATION_JSON));

            response = client.execute(httpEntity);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }
                bufferedReader.close();
                return JSONObject.parseObject(result.toString(), BaseResponse.class);
            }

        } catch (Exception e) {
            log.error("发送请求失败：{}", JSON.toJSONString(request));
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
